package org.wx.herostory.services.encoder;

import io.netty.channel.ChannelHandlerContext;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;
import org.wx.herostory.model.MoveState;
import org.wx.herostory.model.User;
import org.wx.herostory.msg.GameMsgProtocol;
import org.wx.herostory.services.util.Broadcaster;
import org.wx.herostory.services.util.UserManager;

/**
 * @program: my-java
 * @description: 用户移动
 * @author: Wang.xun
 * @create: 2021-03-01 21:57
 **/
@Slf4j
public class UserMoveToCmdHandler implements ICmdHandler<GameMsgProtocol.UserMoveToCmd>{
    @Override
    public void handle(ChannelHandlerContext ctx, GameMsgProtocol.UserMoveToCmd cmd) {
        if(null == ctx || null == cmd){
            return;
        }
        Integer userId = (Integer) ctx.channel().attr(AttributeKey.valueOf("userId")).get();
        log.info("用户{}移动",userId);
        if(null == userId){
            return;
        }
        // 当前用户
        User currUser = UserManager.getUserById(userId);
        if(null == currUser){
            return;
        }

        float moveToPosX = cmd.getMoveToPosX();
        float moveToPosY = cmd.getMoveToPosY();
        float moveFromPosX = cmd.getMoveFromPosX();
        float moveFromPosY = cmd.getMoveFromPosY();

        MoveState userMoveState = currUser.getMoveState();
        // 没有添加移动状态，就生成一个新对象
        if(null == userMoveState){
            userMoveState = new MoveState();
        }
        // 当前时间
        long nowTime = System.currentTimeMillis();
        // 为当前用户设置移动的状态
        userMoveState.setFromPosX(moveFromPosX);
        userMoveState.setFromPosY(moveFromPosY);
        userMoveState.setToPosX(moveToPosX);
        userMoveState.setToPosY(moveToPosY);
        userMoveState.setStartTime(nowTime);




        GameMsgProtocol.UserMoveToResult.Builder builder = GameMsgProtocol.UserMoveToResult.newBuilder();
        builder.setMoveUserId(userId);
        builder.setMoveFromPosX(moveFromPosX);
        builder.setMoveFromPosY(moveFromPosY);
        builder.setMoveToPosX(moveToPosX);
        builder.setMoveToPosY(moveToPosY);
        builder.setMoveStartTime(nowTime);

        GameMsgProtocol.UserMoveToResult moveToResult = builder.build();
        // 广播出去
        Broadcaster.broadcast(moveToResult);
    }
}
